import { getInfo } from '@/api/adminUser'
import { getMenus } from '@/api/menus'

const getDefaultState = () => {
  return {
    name: '',
    menus: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          reject('登录超时，请重新登录')
        }

        const { name } = data

        commit('SET_NAME', name)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getUserMenus({ commit }) {
    return new Promise((resolve, reject) => {
      getMenus().then(response => {
        const { data } = response
        commit('SET_MENUS', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

